package com.olymtech.jbricks.demo.mail;

import com.olymtech.jbricks.demo.mail.model.EmailFrom;
import com.olymtech.jbricks.demo.mail.model.MultipartEmail;
import com.olymtech.jbricks.demo.mail.model.SimpleEmail;
import com.sun.mail.util.MailSSLSocketFactory;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;

import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Map;
import java.util.Properties;

/**
 * @author haoting.wang
 * @date 2020/12/18 10:01 上午
 **/
public class EmailServer {

    private Session session;

    private String fromAccount;

    private String personal;

    public EmailServer(EmailFrom emailFrom) {
        this.fromAccount = emailFrom.getAccount();
        this.personal = emailFrom.getPersonal();
        Properties props = new Properties();
        props.put("mail.transport.protocol", emailFrom.getProtocol());
        props.put("mail.smtp.host", emailFrom.getHost());
        props.put("mail.smtp.port", emailFrom.getPort());
        props.put("mail.smtp.auth", "true");

        //使用SSL，企业邮箱必需！
        //开启安全协议
        MailSSLSocketFactory mailSSLSocketFactory = null;
        try {
            mailSSLSocketFactory = new MailSSLSocketFactory();
            mailSSLSocketFactory.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);

        this.session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailFrom.getAccount(), emailFrom.getPassword());
            }
        });
        this.session.setDebug(true);

    }

    public void sendMail(SimpleEmail email) throws Exception {

        MimeMessage message = new MimeMessage(session);

        if (!StringUtils.isEmpty(personal)) {
            message.setFrom(new InternetAddress(fromAccount, personal));
        } else {
            message.setFrom(new InternetAddress(fromAccount));
        }

        message.setRecipient(Message.RecipientType.TO, new InternetAddress(email.getAccount()));
        // 设置邮件主题
        message.setSubject(email.getTitle(), "UTF-8");
        // 设置邮件正文:
        message.setText(email.getContent(), "UTF-8");
        Transport.send(message);
    }


    public void sendMailMultipart(MultipartEmail email) throws MessagingException, IOException {

        MimeMessage message = new MimeMessage(session);

        if (!StringUtils.isEmpty(personal)) {
            message.setFrom(new InternetAddress(fromAccount, personal));
        } else {
            message.setFrom(new InternetAddress(fromAccount));
        }

        InternetAddress[] sendTo = InternetAddress.parse(email.getTo());
        message.setRecipients(MimeMessage.RecipientType.TO, sendTo);

        //设置收件人地址，以逗号隔开
        if (!StringUtils.isEmpty(email.getCc())) {
            InternetAddress[] carbonCopy = InternetAddress.parse(email.getCc());
            message.setRecipients(MimeMessage.RecipientType.CC, carbonCopy);
        }

        message.setSubject(email.getTitle(), "UTF-8");

        Multipart multipart = new MimeMultipart();

        // 添加内容:
        BodyPart textpart = new MimeBodyPart();
        textpart.setContent(email.getContent(), email.getMimeType());
        multipart.addBodyPart(textpart);

        // 添加附件:
        if (!MapUtils.isEmpty(email.getFiles())) {
            for (Map.Entry<String, String> entry : email.getFiles().entrySet()) {
                BodyPart bodyPart = new MimeBodyPart();
                bodyPart.setFileName(entry.getKey());

                bodyPart.setDataHandler(new DataHandler(new URL(entry.getValue())));
                multipart.addBodyPart(bodyPart);
            }
        }

        message.setContent(multipart);
        Transport.send(message);

    }


    public static void main(String[] args) throws Exception {

        EmailFrom emailFrom = new EmailFrom();

        emailFrom.setAccount("943897692@qq.com");
        emailFrom.setHost("smtp.qq.com");
        emailFrom.setPort("465");
        emailFrom.setPassword("nrxsgpqbmazjbbch");
        emailFrom.setPersonal("我和他");
        emailFrom.setProtocol("smtp");

        EmailServer emailServer = new EmailServer(emailFrom);


//        SimpleEmail simpleEmail = new SimpleEmail();
//        simpleEmail.setAccount("1465528147@qq.com");
//        simpleEmail.setContent("hello wht");
//        simpleEmail.setTitle("主题");
//        emailServer.sendMail(simpleEmail);

//

        MultipartEmail multipartEmail = new MultipartEmail();
        multipartEmail.setTitle("主题测试");
        multipartEmail.setTo("1465528147@qq.com,30682680@qq.com");
        multipartEmail.setContent("<h1>hello</h1><img src=\"https://xqimg.imedao.com/1767fff03f6acbf3fe177ee5.jpg\">");
        multipartEmail.setMimeType("text/html;charset=utf-8");

        Map<String, String> map = new HashedMap();
        map.put("hello.png", "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png");
        map.put("hello123.png", "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png");
        multipartEmail.setFiles(map);
        emailServer.sendMailMultipart(multipartEmail);


    }


}
